/**
 * @file sessionfactory.cpp
 * @brief SessionFactory class methods implementation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * @author VestniK (Sergey N.Vidyuk) sir.vestnik@gmail.com
 * @date 16 Jan 2010
 */
#include "sessionfactory.h"

#include "game.h"
#include "mjntypes.h"
#include "serverplayer.h"

using namespace mjn;

SessionFactory::SessionFactory(Game *game): QObject(game) {
    mGame = game;
}

Session *SessionFactory::create() {
    return new Session(this);
}

/**
 * Collects information about active sessions and send it to clients.
 */
void SessionFactory::notifySessions()
{
    QMap<QUuid,SessionData>::iterator it;
    QList<SessionInfo> sessions;
    for(it = mSessionsDataMap.begin(); it != mSessionsDataMap.end(); it++) {
        SessionInfo info;
        info.name = it.value().player->name();
        // Should never happen but it's better to check
        if (it.value().session.isNull()) it.value().disconnected = true;
        info.disconnected = it.value().disconnected;
        sessions.append(info);
    }
    for(it = mSessionsDataMap.begin(); it != mSessionsDataMap.end(); it++) {
        if (it.value().disconnected) continue;
        it.value().session->sendInfo(sessions);
    }
}

bool SessionFactory::storeData(const QUuid &sid, const SessionData &data) {
    QMap<QUuid,SessionData>::iterator it = mSessionsDataMap.find(sid);
    if ( it != mSessionsDataMap.end() ) {
        return false; // session with such id already exists
    }
    mSessionsDataMap[sid] = data;
    return true;
}

/**
 * @return pointer to data for the session with the sid given or 0 pointer if no
 * session with this sid registered.
 */
SessionData *SessionFactory::getData(const QUuid &sid) {
    QMap<QUuid,SessionData>::iterator it = mSessionsDataMap.find(sid);
    if ( it == mSessionsDataMap.end() ) {
        return 0; // no such session
    }
    return &(*it);
}

/**
 * Removes session data from session data store. This function is called by
 * Session::onClose() function to free data.
 */
void SessionFactory::removeData(const QUuid &sid)
{
    mSessionsDataMap.remove(sid);
}

